/**
 * 使用mongoose 模块调用mongoDB 功能
 * 使用模块需要先安装 npm i mongoose
 * -- 使用 mongoose 中间件  案例
 */
//引入封装好的模块来操作数据
const BooksMod = require("./model/Books");

//  创建静态方法 查询传入的title
// 以下内容保存在model  Books中
// BooksSchema.statics.findByTitle = function (title, cb) {

//   //通过 find方法获取 title的数据    this 关键字获取当前的model,cd是回调
//   this.find({
//     "title": title
//   }, function (err, docs) {
//     cb(err, docs)
//   })
// }

// init();
// init2()
// findOneAndUpdate();
// updateMany();
// findByIdAndRemove();
// insertMany(6);
setTimeout(function () {
  // deleteMany()
  findByIdAndRemove("6212ff352b403baff9f981ca")
}, 1000)


function init() {
  BooksMod.findById("61fcecbf73500000290066f2").then((doc) => {
    // console.log(doc)
    console.log(doc)
  })
}

function init2() {
  let books = new BooksMod({
    name: "增删改查",
    title: "  增删改查 title ",
    url: "www.123.cin",

  })
  books.save(function (err, doc) {
    console.log(doc)
    if (doc) {
      let id = doc._id;
      console.log("id", id)
      updataFn(id)
    }

  })
}

function updataFn(id) {
  BooksMod.findByIdAndUpdate(id, {
    name: "findByIdAndUpdate",
    url: "www"
  }, function (err, doc) {
    console.log("err", err)
    console.log("doc", doc)
  })
}

function findOneAndUpdate() {
  let id = "6212f83afcc6feebcfb801b0";
  BooksMod.findOneAndUpdate({
    title: "增删改查 TITLE"
  }, {
    text: "2222 d  MMM  "
  }, function (err, doc) {
    console.log("err", err)
    console.log("doc", doc)
  })
}

function updateMany() {
  title = "第258章";
  BooksMod.updateMany({
    title: title
  }, {
    text: "2222 d  MMM  "
  }, function (err, doc) {
    console.log("err", err)
    console.log("doc", doc)
  })
}

function findByIdAndRemove() {
  let id = "6212f83afcc6feebcfb801b0";
  BooksMod.findByIdAndRemove({
    _id: id
  }, function (err, doc) {
    console.log("err", err)
    console.log("doc", doc)
  })
}

function insertMany(index) {
  let arr = []
  for (let i = 0; i < index; i++) {
    let books = new BooksMod({
      name: "我的新大明帝国",
      title: "第" + i + "章",
      text: "for _" + i,
      url: "www.baidu.com"
    })
    arr.push(books)
  }
  BooksMod.insertMany(arr, function (err, doc) {
    console.log("err", err)
    console.log("doc", doc)
  })
}

function deleteMany() {
  BooksMod.deleteMany({
    text: /^for _/
  }, function (err, doc) {
    console.log("err", err)
    console.log("doc", doc)
  });
}

function findByIdAndRemove(id) {
  BooksMod.findByIdAndRemove(id, function (err, doc) {
    console.log("err", err)
    console.log("doc", doc)
  });
}